package com.mc.moring.main;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.hjq.permissions.Permission;
import com.mc.moring.R;
import com.mc.moring.app.LogUtils;
import com.mc.moring.base.BaseActivity;
import com.mc.moring.base.HttpCallback;
import com.mc.moring.base.SaveZiLiPageTool;
import com.mc.moring.bean.WebPageContentBean;
import com.mc.moring.bean.getWebLinkConfigBean;
import com.mc.moring.main.modle.PermisosModle;
import com.mc.moring.util.AppManager;
import com.mc.moring.util.GsonUtils;
import com.mc.moring.util.PointMgr;
import com.mc.moring.util.SharePreUtil;
import com.mc.moring.widge.CommonRetentionDialog;
import com.mc.moring.widge.MyDialog;
import com.mc.moring.widge.HeaderViewLayout;
import com.mc.moring.widge.NewWebView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermisosActivity extends BaseActivity {

    HeaderViewLayout headerTitle;
    TextView mTvSms3;
    TextView mTvDiscrepar;
    TextView mTvConfirmar;
    LinearLayout mLlConfirmar;
    NewWebView webview;
    String webContent = "";

    PermisosModle permisosModle = new PermisosModle();

    MyDialog myDialog;

    CommonRetentionDialog retentionDialog;

    public List<String> permissions = new ArrayList<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PointMgr.INSTANCE.sendEvent("cl_app_plata_2");
        Log.e("PointMgr.INSTANCE.sendEvent","cl_app_plata_2");
        setContentView(R.layout.activity_permisos);
        SharedPreferences sharedPreferences = getSharedPreferences("goPermisos", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("goPermisos","false");
        editor.apply();
        init();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {
        AppManager.getAppManager().addActivity(this);
        getWebLinkConfigBean b = new Gson().fromJson(SharePreUtil.getStringData("_getWebLinkConfig"), getWebLinkConfigBean.class);
        if (b == null) return;
        setImmersionBarTextDark(headerViewLayout, true, 0);
        headerTitle = findViewById(R.id.header_title);
        mTvSms3 = findViewById(R.id.text3);
        mTvDiscrepar = findViewById(R.id.tv_discrepar);
        mTvConfirmar = findViewById(R.id.tv_confirmar);
        mLlConfirmar = findViewById(R.id.ll_confirmar);
        webview = findViewById(R.id.webview);
        mTvSms3.setText("Deslice hacia abajo para leer todas las descripciones de permisos");
        mTvDiscrepar.setText("Discrepar");
        mTvConfirmar.setText("Confirmar");
        myDialog = new MyDialog(this);
        retentionDialog = new CommonRetentionDialog(this);

        if ( webContent != null && !webContent.isEmpty() ){
            webview.loadData(webContent, "text/html","UTF-8");
            PointMgr.INSTANCE.sendEvent("app_plata_3");
            Log.e("PointMgr.INSTANCE.sendEvent","cl_app_plata_3");
        }

        myDialog.setDialogViewOnClickListener(new MyDialog.DialogViewOnClickListener() {
            @Override
            public void onClickConfirm() {
                getPermissions();
            }

            @Override
            public void onClickCancel() {
                Intent intent = new Intent(PermisosActivity.this, PrivacyActivity.class);
                startActivity(intent);
            }
        });

        retentionDialog.setDialogViewOnClickListener(new CommonRetentionDialog.DialogViewOnClickListener() {
            @Override
            public void onClickConfirm() {
                getPermissions();
            }

            @Override
            public void onClickCancel() {

                finish();
            }
        });
        mTvDiscrepar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PointMgr.INSTANCE.sendEvent("cl_app_plata_5");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_app_plata_5");
                myDialog.showToPermissionSettingDialog(PermisosActivity.this,"PermisosActivity");
            }
        });

        mTvConfirmar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PointMgr.INSTANCE.sendEvent("cl_app_plata_4");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_app_plata_4");
                String permisosClick = new SaveZiLiPageTool(PermisosActivity.this).getKeyValue("permisosClick");
                if (TextUtils.isEmpty(permisosClick))return;
                getPermissions();
            }
        });
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setOnNewWebViewScroolChangeListener(new NewWebView.ScrollInterface() {
            @Override
            public void onSChanged(int l, int t, int oldl, int oldt) {
                float webcontent = webview.getContentHeight() * webview.getScale();//webview的高度
                if (webcontent == 0) {
                    return;
                }
                if (webview.getHeight() + webview.getScrollY() >= webcontent - 10) {
                    new SaveZiLiPageTool(PermisosActivity.this).puttKeyValue("permisosClick", "1");
                    mTvConfirmar.setBackgroundResource(R.drawable.bg_gradient_b4ffcc_76efff_corner_8);
                }
            }
        });

//        permissions.add(Permission.ACCESS_COARSE_LOCATION);
        permissions.add(Permission.READ_PHONE_STATE);
        permissions.add(Permission.CAMERA);
        setPermissionList(permissions);

    }

    @Override
    public void initData() {


        Map<String, String> webContentMap = new HashMap<>();
        webContentMap.put("pageType","permission");
        PermisosModle.Companion.getInstant().getWebPageContent(webContentMap, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                LogUtils.logE("getWebPageContent ---data:"+data);
                WebPageContentBean webPageContentBean = GsonUtils.INSTANCE.getGson().fromJson(data, WebPageContentBean.class);
                if (webPageContentBean.getCode().equals("0000") && !TextUtils.isEmpty(webPageContentBean.getData())) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webContent = webPageContentBean.getData();
                            if ( webview != null ){
                                webview.loadData(webContent, "text/html","UTF-8");
                                PointMgr.INSTANCE.sendEvent("app_plata_3");
                                Log.e("PointMgr.INSTANCE.sendEvent","cl_app_plata_3");
                            }
                        }
                    });
                } else {
                    loadPermissionUrlByWebLink();
                }
                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                hideLoading();
            }
        });


    }

    private void loadPermissionUrlByWebLink() {
        Map<String, String> map = new HashMap<>();
        PermisosModle.Companion.getInstant().getZiLiPageWebLinkConfig(map, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getWebLinkConfigBean getWebLinkConfig = GsonUtils.INSTANCE.getGson().fromJson(data, getWebLinkConfigBean.class);
                        Log.e("----getWebLinkConfig", GsonUtils.INSTANCE.getGson().toJson(getWebLinkConfig.getData()));
                        if (getWebLinkConfig != null) {
                            try {
                                String permission = getWebLinkConfig.getData().getPermission();
                                webview.loadUrl(permission);
                                PointMgr.INSTANCE.sendEvent("app_plata_3");
                                Log.e("PointMgr.INSTANCE.sendEvent","cl_app_plata_3");
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }
                    }
                });
                hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                LogUtils.logE(e);
                hideLoading();
            }
        });
    }

    public void getPermissions() {
        List<String> permissions = new ArrayList<>();
        permissions.add(Permission.READ_SMS);
        permissions.add(Permission.READ_CALL_LOG);
        permissions.add(Permission.READ_PHONE_STATE);
        permissions.add(Permission.CAMERA);
        String[] permissionStr = new String[]{Manifest.permission.READ_SMS, Manifest.permission.READ_CALL_LOG,
                Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA};
        ActivityCompat.requestPermissions(this, permissionStr, 10001);
//        XXPermissions.with(this).permission(permissions).request(new OnPermissionCallback() {
//            @Override
//            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
//                new SaveZiLiPageTool(PermisosActivity.this).puttKeyValue("permisos", "permisos");
//                Intent intent = new Intent(PermisosActivity.this, PrivacyActivity.class);
//                startActivity(intent);
//                finish();
//            }
//
//            @Override
//            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
//                OnPermissionCallback.super.onDenied(permissions, doNotAskAgain);
//                Intent intent = new Intent(PermisosActivity.this, PrivacyActivity.class);
//                startActivity(intent);
//                finish();
//            }
//        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 10001) {
            if (hasPermission(Manifest.permission.READ_SMS)) {
                PointMgr.INSTANCE.sendEvent("cl_read_sms_yes");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_read_sms_yes");
            }else{
                PointMgr.INSTANCE.sendEvent("cl_read_sms_no");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_read_sms_no");
            }
            if (hasPermission(Manifest.permission.READ_CALL_LOG)) {
                PointMgr.INSTANCE.sendEvent("cl_read_call_log_yes");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_read_call_log_yes");
            }else{
                PointMgr.INSTANCE.sendEvent("cl_read_call_log_no");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_read_call_log_no");
            }
            if (hasPermission(Manifest.permission.READ_PHONE_STATE)) {
                PointMgr.INSTANCE.sendEvent("cl_read_phone_state_yes");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_read_phone_state_yes");
            }else{
                PointMgr.INSTANCE.sendEvent("cl_read_phone_state_no");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_read_phone_state_no");
            }
            if (hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                PointMgr.INSTANCE.sendEvent("cl_access_fine_location_yes");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_access_fine_location_yes");
            }else{
                PointMgr.INSTANCE.sendEvent("cl_access_fine_location_no");
                Log.e("PointMgr.INSTANCE.sendEvent","cl_access_fine_location_no");
            }
            new SaveZiLiPageTool(PermisosActivity.this).puttKeyValue("permisos", "permisos");
            Intent intent = new Intent(PermisosActivity.this, PrivacyActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String permisos = new SaveZiLiPageTool(PermisosActivity.this).getKeyValue("permisos");
        if (TextUtils.isEmpty(permisos)){
            new SaveZiLiPageTool(PermisosActivity.this).puttKeyValue("permisosClick", null);
        }
    }


    @Override
    public void onBackPressed() {
        retentionDialog.showToRetentionDialog(PermisosActivity.this);
    }

    private Boolean hasPermission(String permission) {
        return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
    }
}
